package com.cloud.server.system.config;

import com.cloud.common.core.handler.MyAccessDeniedHandler;
import com.cloud.common.core.handler.MyAuthExceptionEntryPoint;
import com.cloud.server.system.properties.ServerSystemProperties;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;


/**
 * @Description:
 * @Auther: zhangxun
 * @Date: 2020/8/7 20:09
 */
@Data  // 少了这个 anonUrls 注入不进去
@Configuration
@EnableResourceServer
@ConfigurationProperties(prefix = "system.config")
public class ResourceServerConfigure extends ResourceServerConfigurerAdapter {
    @Autowired
    private MyAccessDeniedHandler accessDeniedHandler;
    @Autowired
    private MyAuthExceptionEntryPoint exceptionEntryPoint;
    @Autowired
    private ServerSystemProperties properties;

    private String[] anonUrls;
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    //表示所有访问febs-server-system的请求都需要认证，只有通过认证服务器发放的令牌才能进行访问。
    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
                .requestMatchers().antMatchers("/**")
                .and()
                .authorizeRequests()
                .antMatchers(anonUrls).permitAll()
                .antMatchers("/**").authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) {
        resources.authenticationEntryPoint(exceptionEntryPoint)
                .accessDeniedHandler(accessDeniedHandler);
    }
}